//
//  NewFeatureViewController.swift
//  SynWeibo
//
//  Created by 沈艳男 on 15/9/6.
//  Copyright © 2015年 沈艳男. All rights reserved.
//

import UIKit

private let NewFeatureCellID = "CellID"
// 性特性是图片数量
private let NewFeatureCount = 4

class NewFeatureViewController: UICollectionViewController {

    // 初始化 init() 构造函数，
    // 作用是：当调用该控制器时会初始化布局
    init() {
        super.init(collectionViewLayout: UICollectionViewFlowLayout())
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView!.registerClass(NewFeatureCell.self, forCellWithReuseIdentifier: NewFeatureCellID)
        NewFeaturelayout()
    }
    
    // 设置collectionView的布局属性
    private func NewFeaturelayout() {
        // 获取当前的布局属性
        let layout = collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
        
        layout.itemSize = view.bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        // 设置滚动方向为，横向
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        // 分页属性
        collectionView?.pagingEnabled = true
        // 去掉弹簧属性
        collectionView?.bounces = false
        // 去掉水平滚动条
        collectionView?.showsHorizontalScrollIndicator = false
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: UICollectionViewDataSource
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return NewFeatureCount
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(NewFeatureCellID, forIndexPath: indexPath) as! NewFeatureCell
    
        // Configure the cell
//        cell.backgroundColor = (indexPath.item % 2 == 0) ? UIColor.redColor() : UIColor.blackColor()
        cell.imageIndex = indexPath.item
        return cell
    }
    
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        
        // 获取当前显示的cell的索引indexPath
        let indexPath = collectionView.indexPathsForVisibleItems().last!
        
        // 判断是否是最后一个,
        if indexPath.item == NewFeatureCount - 1 {
            // 获取cell
            let cell = collectionView.cellForItemAtIndexPath(indexPath) as! NewFeatureCell
            // 显示最后一张图片
            cell.showStartButton()
        }
        
    }

}

private class NewFeatureCell: UICollectionViewCell {
    // 懒加载控件
    private lazy var iconView = UIImageView()
    private lazy var startButton: UIButton = {
        let button = UIButton()
        
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        button.setTitle("开始体验", forState: UIControlState.Normal)
        
        button.addTarget(self, action: "buttonClick", forControlEvents: UIControlEvents.TouchUpInside)
        button.sizeToFit()
        return button
        
    }()
    
    @objc func buttonClick() {
        print("开始体验")
        NSNotificationCenter.defaultCenter().postNotificationName(HMSwitchRootViewControllerNotification, object: nil)
        
    }
    
    private func setUI() {
        
        // 1、添加控件
        addSubview(iconView)
        addSubview(startButton)
        
        // 2、指定布局
        iconView.frame = bounds
        startButton.frame = bounds
        startButton.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
        addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -160))
        
    }
    
    private func showStartButton() {
        startButton.hidden = false
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        
        // Damping 弹性系数，0~1，越小越弹
        // Velocity: 初始速度
        UIView.animateWithDuration(1.25, delay: 0.0, usingSpringWithDamping: 0.25, initialSpringVelocity: 8, options: [], animations: { () -> Void in
            self.startButton.transform = CGAffineTransformIdentity
            }) { (_) -> Void in
                //
        }
    }
    
    // 设置图像的索引
    private var imageIndex: Int = 0 {
        didSet {
            iconView.image = UIImage(named: "new_feature_\(imageIndex + 1)")
            startButton.hidden = true
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setUI()
    }
    

    
}